//
//  iFLYHandler.m
//  Project_B
//
//  Created by 甘霞 on 15/11/30.
//  Copyright © 2015年 Atom_Wang. All rights reserved.
//

#import "iFLYHandler.h"
#import <iflyMSC/iflyMSC.h>
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>

@interface iFLYHandler () <IFlySpeechRecognizerDelegate>

//  识别对象
@property (nonatomic, strong) IFlySpeechRecognizer *iFlySpeechRecognizer;
//  是否取消
@property (nonatomic, assign) BOOL isCanceled;
//  结果字符串
@property (nonatomic, copy) NSString *result;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, assign) int vol;

@end

@implementation iFLYHandler

- (instancetype)init {
    self = [super init];
    if (self) {
        //  初始化识别对象
        [self initRecognizer];
    }
    return self;
}

#pragma mark - 初始化识别对象
- (void)initRecognizer {
    //单例模式
    if (_iFlySpeechRecognizer == nil) {
        
        _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
        
        [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        
        //设置听写模式
        [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
    }
    
    _iFlySpeechRecognizer.delegate = self;
    
    if (_iFlySpeechRecognizer != nil) {
        
        //设置最长录音时间
        [_iFlySpeechRecognizer setParameter:@"30000" forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
        //设置后端点
        [_iFlySpeechRecognizer setParameter:@"3000" forKey:[IFlySpeechConstant VAD_EOS]];
        //设置前端点
        [_iFlySpeechRecognizer setParameter:@"3000" forKey:[IFlySpeechConstant VAD_BOS]];
        //网络等待时间
        [_iFlySpeechRecognizer setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
        //设置采样率
        [_iFlySpeechRecognizer setParameter:@"16000" forKey:[IFlySpeechConstant SAMPLE_RATE]];
        //设置语言
        [_iFlySpeechRecognizer setParameter:@"zh_cn" forKey:[IFlySpeechConstant LANGUAGE]];
        //设置是够返回标点符号
        [_iFlySpeechRecognizer setParameter:@"1" forKey:[IFlySpeechConstant ASR_PTT]];
    }
}

#pragma mark - IFlySpeechRecognizerDelegate 
//  音量回调函数 volume 0 - 30
- (void)onVolumeChanged:(int)volume {
    
    if (self.isCanceled) {
        NSLog(@"识别取消了");
        return;
    }
    
    [self.alertController setMessage:[NSString stringWithFormat:@"音量: %d", volume]];
    
    //  如果分贝一直为0
    if (volume <= 0) {  //几乎为静音
        if (!self.timer) {
            
            self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0f
                                                          target:self
                                                        selector:@selector(observeVolume:)
                                                        userInfo:nil
                                                         repeats:NO];
        }
    } else {    //有说话
        
        
        //只要说一句 - -就把时间推迟两秒 口亨╭(╯^╰)╮
        NSDate *time = [NSDate dateWithTimeIntervalSinceNow:2.0];
        [self.timer setFireDate:time];
        
#if 0   //  频繁创建销毁
        [self.timer invalidate];
        self.timer = nil;
#endif
        
    }
    
    self.vol = volume;
    NSString *vol = [NSString stringWithFormat:@"音量: %d", volume];
    NSLog(@"❤️ 音量: %@", vol);
}

- (void)observeVolume:(NSTimer *)timer {
    
    [self stopToListening];
}

- (void)onBeginOfSpeech {
    NSLog(@"❤️ 正在录音");
}

- (void)onEndOfSpeech {
    NSLog(@"❤️ 停止录音");
    [self.delegate removeAlert];
    self.alertController = nil;
}

/**
 *  Description 听写结束回调(无论听写是否正确都会回调)
 *
 *  @param errorCode 0 听写正确 other 听写出错
 */
- (void)onError:(IFlySpeechError *)errorCode {
    NSString *text;
    if (self.isCanceled) {
        text = @"识别取消";
    } else if (errorCode.errorCode == 0) {
        if (_result != nil) {
            if (_result.length == 0) {
                text = @"无识别结果";
            } else {
                text = @"识别成功";
            }
        }
    } else {
        text = [NSString stringWithFormat:@"发生错误: %d %@", errorCode.errorCode, errorCode.errorDesc];
        NSLog(@"%@", text);
    }
    
    NSLog(@"识别结束");
    NSLog(@"errorCode:%d", [errorCode errorCode]);
}

/**
 解析听写json格式的数据
 params例如：
 {"sn":1,"ls":true,"bg":0,"ed":0,"ws":[{"bg":0,"cw":[{"w":"白日","sc":0}]},{"bg":0,"cw":[{"w":"依山","sc":0}]},{"bg":0,"cw":[{"w":"尽","sc":0}]},{"bg":0,"cw":[{"w":"黄河入海流","sc":0}]},{"bg":0,"cw":[{"w":"。","sc":0}]}]}
 ****/
- (NSString *)stringFromJson:(NSString*)params
{
    if (params == NULL) {
        return nil;
    }
    
    NSMutableString *tempStr = [[NSMutableString alloc] init];
    NSDictionary *resultDic  = [NSJSONSerialization JSONObjectWithData:    //返回的格式必须为utf8的,否则发生未知错误
                                [params dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
    
    if (resultDic!= nil) {
        NSArray *wordArray = [resultDic objectForKey:@"ws"];
        
        for (int i = 0; i < [wordArray count]; i++) {
            NSDictionary *wsDic = [wordArray objectAtIndex: i];
            NSArray *cwArray = [wsDic objectForKey:@"cw"];
            
            for (int j = 0; j < [cwArray count]; j++) {
                NSDictionary *wDic = [cwArray objectAtIndex:j];
                NSString *str = [wDic objectForKey:@"w"];
                [tempStr appendString: str];
            }
        }
    }
    return tempStr;
}

- (void)onCancel {
    NSLog(@"识别取消");
}

//  听写结果回调
- (void)onResults:(NSArray *)results isLast:(BOOL)isLast {
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = results[0];
    NSLog(@"~~~~~%ld", results.count);
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@", key];
    }
    
    _result = [NSString stringWithFormat:@"%@%@", _outputStr, resultString];
    NSString *resultFromJson = [self stringFromJson:resultString];
    _outputStr = [NSString stringWithFormat:@"%@%@", _outputStr, resultFromJson];
    
    if (isLast) {
        NSLog(@"听写结果(json): %@", self.result);
        
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"listenResult" object:nil userInfo:@{@"result" : resultFromJson}];
    
    NSLog(@"☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️");
    NSLog(@"_result = %@", _result);
    NSLog(@"resultFromJson=%@", resultFromJson);
    NSLog(@"isLast=%d, _textField=%@", isLast, _outputStr);
}

- (void)startToListening {
    NSLog(@"❤️开始监听语音");
    self.isCanceled = NO;
    if (_iFlySpeechRecognizer == nil) {
        [self initRecognizer];
    }
    //  取消本次会话
    [_iFlySpeechRecognizer cancel];
    //设置音频来源为麦克风
    [_iFlySpeechRecognizer setParameter:@"json" forKey:[IFlySpeechConstant RESULT_TYPE]];
    //保存录音文件
    [_iFlySpeechRecognizer setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
    [_iFlySpeechRecognizer setDelegate:self];
    
    BOOL ret = [_iFlySpeechRecognizer startListening];
    
    if (ret) {
        NSLog(@"哈哈哈");
        
        self.alertController = [UIAlertController alertControllerWithTitle:@"" message:@"开始听写" preferredStyle: UIAlertControllerStyleAlert];
        [self.delegate showAlert];
        
    } else {
        NSLog(@"启动识别服务失败, 请稍后重试");
    }
}

- (void)stopToListening {
    NSLog(@"结束");
    //  停止录音
    [_iFlySpeechRecognizer cancel];
    [_iFlySpeechRecognizer stopListening];
}

@end